
import mss
import pygetwindow as gw
import numpy as np
import cv2
import time

from utils import press_key, click_mouse, activate_window,mouse_scroll

class TaskHandler:
    def __init__(self):
        window = gw.getWindowsWithTitle('Dungeon & Fighter')[0]
        if not window:
            raise Exception("未找到 DNF 窗口")
        self.monitor  = {
            "top": window.top,
            "left": window.left,
            "width": window.width,
            "height": window.height
        }
        img_fold = "data/img/"
        self.img_task_sign = cv2.imread(img_fold+'task_sign.png',cv2.IMREAD_UNCHANGED)
        self.img_task_daily = cv2.imread(img_fold+'task_daily.png',cv2.IMREAD_UNCHANGED)
        self.img_task_stand = cv2.imread(img_fold+'task_stand.png',cv2.IMREAD_UNCHANGED)

    def capture(self) -> np.ndarray:
        with mss.mss() as sct:
            raw = sct.grab(self.monitor)
            img = np.array(raw)[:, :, :3]
            return img

    def finish_task(self):
        # 1. 读取图片
        img_nd = self.capture()
        
        gray = cv2.cvtColor(img_nd, cv2.COLOR_BGR2GRAY)
        _, mask = cv2.threshold(gray, 200, 255,cv2.THRESH_BINARY)

        method = cv2.TM_CCOEFF_NORMED      # 推荐这个，对光照不敏感
        # method = cv2.TM_CCORR_NORMED     # 也很好

        res = cv2.matchTemplate(mask, self.img_task_sign, method)
        # 4. 找到最佳匹配位置
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        if max_val < 0.8:
            print("未找到任务图标")
            return False
        if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
            top_left = min_loc
        else:
            top_left = max_loc

        h, w = self.img_task_sign.shape[:2]

        print(f"匹配置信度: {max_val:.3f}  (越接近1越好，通常 >0.8 就很可靠)")
        x = top_left[0]
        y = top_left[1]

        click_mouse(x+w//2, y+h//2, clicks=3)
        time.sleep(0.5)
        for _ in range(4):
            press_key('enter')
            time.sleep(0.3)
        # 选取奖励
        click_mouse(435, 525, clicks=3)
        time.sleep(0.5)
        # 点击完成
        click_mouse(859, 568, clicks=1)
        time.sleep(0.5)
        # 确认奖励
        for _ in range(5):
            press_key('enter')
            time.sleep(0.3)

        # # 退出任务界面
        press_key('f2')
        time.sleep(0.5)
        return True
        # 检测有无完成任务. 通过叹号

    def handle_task_daily(self):
        print("handle_task_daily")
        # 每日任务, 只要完成就行
        # 1. 读取图片
        time.sleep(0.5)
        press_key('f2')
        time.sleep(0.5)
        img_nd = self.capture()
        
        gray = cv2.cvtColor(img_nd, cv2.COLOR_BGR2GRAY)
        _, mask = cv2.threshold(gray, 200, 255,cv2.THRESH_BINARY)
        method = cv2.TM_CCOEFF_NORMED      # 推荐这个，对光照不敏感
        # method = cv2.TM_CCORR_NORMED     # 也很好

        res = cv2.matchTemplate(mask, self.img_task_daily, method)
        # 4. 找到最佳匹配位置
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        if max_val < 0.8:
            print("未找到任务 img_task_daily 图标")
            time.sleep(0.5)
            press_key('f2')
            return
 
        if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
            top_left = min_loc
        else:
            top_left = max_loc

        h, w = self.img_task_sign.shape[:2]

        print(f"匹配置信度: {max_val:.3f}  (越接近1越好，通常 >0.8 就很可靠)")
        x = top_left[0]
        y = top_left[1]

        click_mouse(x+w//2, y+h//2, clicks=3)
        time.sleep(0.5)
        for _ in range(4):
            press_key('enter')
            time.sleep(0.3)
        time.sleep(0.3)
        click_mouse(435, 525, clicks=3)
        time.sleep(0.3)
        click_mouse(789, 568, clicks=1)
        time.sleep(0.3)
        self.finish_task()
     

    def handle_task_stand(self):
        print("handle_task_stand")
        # 1. 读取图片
        time.sleep(0.5)
        press_key('f2')
        time.sleep(0.5)
        
        for mouse_sco in [-10,3,3]:
            mouse_scroll(350, 444, delta_y=mouse_sco)
            time.sleep(0.5)
            img_nd = self.capture()
            gray = cv2.cvtColor(img_nd, cv2.COLOR_BGR2GRAY)
            _, mask = cv2.threshold(gray, 200, 255,cv2.THRESH_BINARY)
            method = cv2.TM_CCOEFF_NORMED      # 推荐这个，对光照不敏感
            # method = cv2.TM_CCORR_NORMED     # 也很好
            
            res = cv2.matchTemplate(mask, self.img_task_stand, method)
            # 4. 找到最佳匹配位置
            min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
            if max_val > 0.8:
                break
        else:
            print("未找到任务 img_task_daily 图标")
            return
 
        if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
            top_left = min_loc
        else:
            top_left = max_loc

        h, w = self.img_task_sign.shape[:2]
        bottom_right = (top_left[0] + w, top_left[1] + h)

        print(f"匹配置信度: {max_val:.3f}  (越接近1越好，通常 >0.8 就很可靠)")
        x = top_left[0]
        y = top_left[1]

        click_mouse(x+w//2, y+h//2, clicks=3)
        time.sleep(0.5)
        for _ in range(4):
            press_key('enter')
            time.sleep(0.3)
        time.sleep(0.5)
        click_mouse(435, 525, clicks=3)
        time.sleep(0.5)
        click_mouse(789, 568, clicks=1)
        time.sleep(0.5)
        press_key('f2')
        # 检测有无完成任务. 通过叹号
     
    def renew_task_stand(self):
        print("renew_task_stand")
        # 1. 读取图片
        time.sleep(0.5)
        press_key('f1')
        time.sleep(0.5)
        img_nd = self.capture()
        
        gray = cv2.cvtColor(img_nd, cv2.COLOR_BGR2GRAY)
        _, mask = cv2.threshold(gray, 200, 255,cv2.THRESH_BINARY)
        method = cv2.TM_CCOEFF_NORMED      # 推荐这个，对光照不敏感
        # method = cv2.TM_CCORR_NORMED     # 也很好

        res = cv2.matchTemplate(mask, self.img_task_stand, method)
        # 4. 找到最佳匹配位置
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        if max_val < 0.8:
            print("未找到任务 img_task_stand 图标")
            return 
 
        if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
            top_left = min_loc
        else:
            top_left = max_loc

        h, w = self.img_task_sign.shape[:2]

        print(f"匹配置信度: {max_val:.3f}  (越接近1越好，通常 >0.8 就很可靠)")
        x = top_left[0]
        y = top_left[1]

        click_mouse(x+w//2, y+h//2, clicks=3)
        time.sleep(0.5)
        # 放弃
        click_mouse(477, 470, clicks=1)
        time.sleep(0.5)
        # 确认
        click_mouse(407, 470, clicks=1)
        time.sleep(0.5)
        press_key('f1')
        time.sleep(0.5)


if __name__ == '__main__':
    TH = TaskHandler()
    if TH.finish_task():
        time.sleep(0.5)
        TH.handle_task_stand()
    # time.sleep(0.5)
    # TH.renew_task_stand()
    # TH.finish_task()
